﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using MediaPortal.Configuration;
using MediaPortal.GUI.Library;
using NLog;
using dlCentral.GUI;
using dlCentral.Localizations;
using dlCentral.Settings;
using dlCentral.Settings.Data;
using dlCentral.Utils;

using dlCentral.Scrapper;  
 
namespace dlCentral.ConfigForm { 
    [PluginIcons("dlCentral.Config.Images.dlCentral_Icon_Enabled.png", "dlCentral.Config.Images.dlCentral_Icon_Disabled.png")]
    public partial class ConfigForm : Form, ISetupForm {
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private dlCentralCore core = dlCentralCore.Instance;
        private SettingsSites RTSites = new SettingsSites();
        private SettingsTVSeries RTTVSeries = new SettingsTVSeries();
        private AddConfigForm asf = new AddConfigForm();
        private int PrevSiteIndex = -1;
        //private bool loaded = false;

        public ConfigForm() {
            InitializeComponent();
        }

        #region Load / Save / Cancel
        private void initConfigForm() {
            //loaded = false;
            lblProductVersion.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
        }

        private void ConfigForm_Load(object sender, EventArgs e) {
 
            Cursor.Current = Cursors.WaitCursor;
            try {
                // clears the components and stuff
                initConfigForm();
                fillGeneralFromSettings();
                fillSitesFromSettings();
                fillTVSeriesFromSettings();
                fillProtocolsFromSettings();
                fillSiteTypesFromSettings(); 
            }
            finally {
                Cursor.Current = Cursors.Default;
            }
        }

        private void btnSave_Click(object sender, EventArgs ea) {
            Cursor.Current = Cursors.WaitCursor;
            try {

                saveAllSettings();


                logger.Info("Saving settings to {0}...", dlCentralUtils.SettingsFileName);
                SettingsManager.Save();
                logger.Info("Saving settings to {0} successful.", dlCentralUtils.SettingsFileName);

                Cursor.Current = Cursors.Default;
                Close();
            }
            catch (Exception e) {
                Cursor.Current = Cursors.Default;
                logger.ErrorException(string.Format("Configuration failed to save settings to {0}\n", dlCentralUtils.SettingsFileName), e);
                MessageBox.Show("There was an error when saving the settings file to " +
                    Config.GetFile(Config.Dir.Config, dlCentralUtils.SettingsFileName) + ".\n\n" + e.Message,
                    "Error saving settings", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        #endregion

        #region ISetupForm Members
        // Returns the name of the plugin which is shown in the plugin menu 
        public string PluginName() {
            return dlCentralUtils.PluginName();
        }

        // Returns the description of the plugin is shown in the plugin menu     
        public string Description() {
            return "A plugin that will allow you to download movies or TV shows.";
        }

        // Returns the author of the plugin which is shown in the plugin menu     
        public string Author() {
            return "Gup";
        }

        // show the setup dialog    
        public void ShowPlugin() {
            core.Initialize();
            logger.Info("Launching Configuration Screen");
            ConfigForm config = new ConfigForm();
            config.ShowDialog();
            //this.ShowDialog();
        }

        // Indicates whether plugin can be enabled/disabled      
        public bool CanEnable() {
            return true;
        }

        // get ID of windowplugin belonging to this setup    
        public int GetWindowId() {
            return 181966;
        }

        // Indicates if plugin is enabled by default
        public bool DefaultEnabled() {
            return true;
        }

        // indicates if a plugin has its own setup screen     
        public bool HasSetup() {
            return true;
        }

        public bool GetHome(out string strButtonText, out string strButtonImage, out string strButtonImageFocus, out string strPictureImage) {
            strButtonText = dlCentralUtils.PluginName();
            strButtonImage = string.Empty;
            strButtonImageFocus = string.Empty;
            strPictureImage = "";
            return false;
        }
        #endregion

 
        private void fillGeneralFromSettings()
        {
            if (Settings.SettingsManager.Properties.GeneralSettings != null)
            {
                tbCommPath.Text = Settings.SettingsManager.Properties.GeneralSettings.CommPath;
                if (!String.IsNullOrEmpty(Settings.SettingsManager.Properties.GeneralSettings.CommTimeOut))
                     SiteTimeOutnumericUpDown.Value = Convert.ToInt32(Settings.SettingsManager.Properties.GeneralSettings.CommTimeOut);
                
                
            }
   
        }
        private void fillSitesFromSettings()
        {
            lbSites.BeginUpdate();
            try
            {

                if (Settings.SettingsManager.Properties.SiteSettings.Sites == null || Settings.SettingsManager.Properties.SiteSettings.Sites.Count == 0) return;
                foreach (SettingsSite site in Settings.SettingsManager.Properties.SiteSettings.Sites)
                {
                    RTSites.Sites.Add(site);
                    lbSites.Items.Add(site.SiteName);
                }
            }
            finally
            {
                lbSites.EndUpdate();
            }
        }

        private void fillTVSeriesFromSettings()
        {
            lvTVSeries.BeginUpdate();
            try
            {
                if (Settings.SettingsManager.Properties.TVSeriesSettings.TVseries == null || Settings.SettingsManager.Properties.TVSeriesSettings.TVseries.Count == 0) return;
                foreach (TVSeries tvseries in Settings.SettingsManager.Properties.TVSeriesSettings.TVseries)
                {
                    RTTVSeries.TVseries.Add(tvseries);
                    ListViewItem item = new ListViewItem(new[] { tvseries.OriginalName, tvseries.ModifiedName,
                                                                 tvseries.Separator, tvseries.SeasonFormat, tvseries.EpisodeFormat });
                    lvTVSeries.Items.Add(item); 
                }
                tbTVSeriesSeparator.Text = Settings.SettingsManager.Properties.TVSeriesSettings.DefaultSeparator;
                tbTVSeriesSeasonFormat.Text = Settings.SettingsManager.Properties.TVSeriesSettings.DefaultSeasonFormat;
                tbTVSeriesEpisodeFormat.Text = Settings.SettingsManager.Properties.TVSeriesSettings.DefaultEpisodeFormat;
            }
            finally
            {
                lvTVSeries.EndUpdate();
            }
        }

        private void fillProtocolsFromSettings()
        {
            cbProtocol.BeginUpdate();
            try
            {

                if (Settings.SettingsManager.Properties.ProtocolSettings.Protocol == null || Settings.SettingsManager.Properties.ProtocolSettings.Protocol.Count == 0)
                {
                    for (int i = 0; i < dlCentralUtils.ProtocolStrings.Count; i++)
                    {
                        ProtocolType p2 = new ProtocolType();
                        p2.ProtocolCode = dlCentralUtils.ProtocolTypes[i];
                        p2.ProtocolDescription = dlCentralUtils.ProtocolStrings[i];
                        Settings.SettingsManager.Properties.ProtocolSettings.Protocol.Add(p2);
                        cbProtocol.Items.Add(p2.ProtocolDescription);
                    }
                }
                else
                    foreach (ProtocolType p1 in Settings.SettingsManager.Properties.ProtocolSettings.Protocol)
                {
                    cbProtocol.Items.Add(p1.ProtocolDescription);
                }
            }
            finally
            {
                cbProtocol.EndUpdate();
            }
        }

        private void fillSiteTypesFromSettings()
        {
            cbSiteType.BeginUpdate();
            try
            {

                if (Settings.SettingsManager.Properties.SiteTypesSettings.SiteTypes == null || Settings.SettingsManager.Properties.SiteTypesSettings.SiteTypes.Count == 0)
                {
                    for (int i = 0; i < dlCentralUtils.SiteTypes.Count; i++)
                    {
                        SiteType s2 = new SiteType();
                        s2.SiteTypeCode = dlCentralUtils.SiteTypes[i];
                        s2.SiteTypeDescription = dlCentralUtils.SiteTypeStrings[i];
                        Settings.SettingsManager.Properties.SiteTypesSettings.SiteTypes.Add(s2);
                        cbSiteType.Items.Add(s2.SiteTypeDescription);
                    }
                }
                else
                    foreach (SiteType s1 in Settings.SettingsManager.Properties.SiteTypesSettings.SiteTypes)
                    {
                        cbSiteType.Items.Add(s1.SiteTypeDescription);
                    }
            }
            finally
            {
                cbSiteType.EndUpdate();
            }
        }
 
        private void saveAllSettings() {
       
            Settings.SettingsManager.Properties.SiteSettings.Sites.Clear();
            //     Force Update last item
            lbSites.SelectedIndex = -1;

            Settings.SettingsManager.Properties.GeneralSettings.CommPath = tbCommPath.Text;
            Settings.SettingsManager.Properties.GeneralSettings.CommTimeOut = SiteTimeOutnumericUpDown.Value.ToString(); 
            foreach (SettingsSite SiteItem in RTSites.Sites)
            {
                Settings.SettingsManager.Properties.SiteSettings.Sites.Add(SiteItem);
            }

            Settings.SettingsManager.Properties.TVSeriesSettings.TVseries.Clear();
            foreach (TVSeries TVSeriesItem in RTTVSeries.TVseries)
            {
                Settings.SettingsManager.Properties.TVSeriesSettings.TVseries.Add(TVSeriesItem);
            }
            Settings.SettingsManager.Properties.TVSeriesSettings.DefaultSeparator = tbTVSeriesSeparator.Text;
            Settings.SettingsManager.Properties.TVSeriesSettings.DefaultSeasonFormat = tbTVSeriesSeasonFormat.Text;
            Settings.SettingsManager.Properties.TVSeriesSettings.DefaultEpisodeFormat = tbTVSeriesEpisodeFormat.Text;

        }


        private void SetAddForm(string[] arr)
        {
            int i = 0;
            if (arr[0] != "") asf.Text = arr[0];
            if (arr[1] != "")
            {
                asf.label1.Text = arr[1];
                asf.label1.Show();
                asf.textBox1.Show();
                asf.textBox1.Text = "";
                i++;
            }
            else
            {
                asf.label1.Hide();
                asf.textBox1.Hide();
            }
            if (arr[2] != "")
            {
                asf.label2.Text = arr[2];
                asf.label2.Show();
                asf.textBox2.Text = "";
                asf.textBox2.Show();
                i++;
            }
            else
            {
                asf.label2.Hide();
                asf.textBox2.Hide();
                i++;
            }
            if (arr[3] != "")
            {
                asf.label3.Text = arr[3];
                asf.label3.Show();
                asf.textBox3.Text = "";
                asf.textBox3.Show();
                i++;
            }
            else
            {
                asf.label3.Hide();
                asf.textBox3.Hide();
            }
            if (arr[4] != "")
            {
                asf.label4.Text = arr[4];
                asf.label4.Show();
                asf.textBox4.Text = "";
                asf.textBox4.Show();
                i++;
            }
            else
            {
                asf.label4.Hide();
                asf.textBox4.Hide();
            }
            if (arr[5] != "")
            {
                asf.label5.Text = arr[5];
                asf.label5.Show();
                asf.textBox5.Text = "";
                asf.textBox5.Show();
                i++;
            }
            else
            {
                asf.label5.Hide();
                asf.textBox5.Hide();
            }
            asf.Height = (i * 40) + 100;
            asf.gbGeneral.Height = (i * 40) + 20;
        }


        private string GetProtocol(string str)
        {
            
            foreach (ProtocolType p1 in Settings.SettingsManager.Properties.ProtocolSettings.Protocol)
            {
                if (str == p1.ProtocolDescription) return p1.ProtocolCode;
                if (str == p1.ProtocolCode) return p1.ProtocolDescription;
            }
            return string.Empty;
        }

        private string GetSiteType(string str)
        {

            foreach (SiteType s1 in Settings.SettingsManager.Properties.SiteTypesSettings.SiteTypes)
            {
                if (str == s1.SiteTypeDescription) return s1.SiteTypeCode;
                if (str == s1.SiteTypeCode) return s1.SiteTypeDescription;
            }
            return string.Empty;
        }



        private void labelIcons_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            Process.Start(@"http://www.famfamfam.com/");
        }

        private void labelGoogleCode_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            Process.Start(@"http://code.google.com/p/dlcentral/");
        }

        private void labelManual_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            Process.Start(@"http://code.google.com/p/dlcentral/wiki/Manual");
        }

        private void labelForum_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            Process.Start(@"http://forum.team-mediaportal.com/mediaportal-plugins-47/dlCentral-85545/");
        }

        private void LabelSCRU_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start(@"http://www.codebyte.org/scru.php");
        }

        private void lbSites_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (PrevSiteIndex != -1)
            {
                RTSites.Sites[PrevSiteIndex].SiteType = GetSiteType(cbSiteType.Text);
                RTSites.Sites[PrevSiteIndex].Host = tbHost.Text;
                RTSites.Sites[PrevSiteIndex].Protocol = GetProtocol(cbProtocol.Text);
                RTSites.Sites[PrevSiteIndex].Port = tbPort.Text;
                RTSites.Sites[PrevSiteIndex].PASV = cbPasv.Checked;
                RTSites.Sites[PrevSiteIndex].UserName = tbUserName.Text;
                RTSites.Sites[PrevSiteIndex].Password = tbPassword.Text;
                RTSites.Sites[PrevSiteIndex].TVLocalDir = FileUtils.ensureBackSlash(tbTVLocalDir.Text);
                RTSites.Sites[PrevSiteIndex].MovieLocalDir = FileUtils.ensureBackSlash(tbMovieLocalDir.Text);
                RTSites.Sites[PrevSiteIndex].MP3LocalDir = FileUtils.ensureBackSlash(tbMP3LocalDir.Text);
                RTSites.Sites[PrevSiteIndex].SearchTerm = tbSearchTerm.Text;
            }
            int i = lbSites.SelectedIndex;
            if (i != -1)
            {
                cbSiteType.Text = GetSiteType(RTSites.Sites[i].SiteType);
                tbHost.Text = RTSites.Sites[i].Host;
                cbProtocol.Text = GetProtocol(RTSites.Sites[i].Protocol);
                tbPort.Text = RTSites.Sites[i].Port;
                cbPasv.Checked = RTSites.Sites[i].PASV;
                tbUserName.Text = RTSites.Sites[i].UserName;
                tbPassword.Text = RTSites.Sites[i].Password;
                tbTVLocalDir.Text = RTSites.Sites[i].TVLocalDir;
                tbMovieLocalDir.Text = RTSites.Sites[i].MovieLocalDir;
                tbMP3LocalDir.Text = RTSites.Sites[i].MP3LocalDir;
                tbSearchTerm.Text = RTSites.Sites[i].SearchTerm;

                tvSites.Nodes[0].Nodes.Clear();
                foreach (string str in RTSites.Sites[i].TVRemoteDirs)
                {
                    tvSites.Nodes[0].Nodes.Add(str);
                }
                tvSites.Nodes[1].Nodes.Clear();
                foreach (string str in RTSites.Sites[i].MovieRemoteDirs)
                {
                    tvSites.Nodes[1].Nodes.Add(str);
                }
                tvSites.Nodes[2].Nodes.Clear();
                foreach (string str in RTSites.Sites[i].MP3RemoteDirs)
                {
                    tvSites.Nodes[2].Nodes.Add(str);
                }
            }
            else
            {
                cbSiteType.Text = "";
                tbHost.Text = "";
                cbProtocol.Text = "";
                tbPort.Text = "";
                tbUserName.Text = "";
                tbPassword.Text = "";
                tbTVLocalDir.Text = "";
                tbMovieLocalDir.Text = "";
                tbMP3LocalDir.Text = "";
                tvSites.Nodes[0].Nodes.Clear();
                tvSites.Nodes[1].Nodes.Clear();
                tvSites.Nodes[2].Nodes.Clear();
            }
            PrevSiteIndex = i;

        }

        private void addMI_Click(object sender, EventArgs e)
        {
            if (cMenuSites.SourceControl.Equals(tvSites))
            {
                int i = lbSites.SelectedIndex;
                if (i == -1) return;
                if (tvSites.SelectedNode.Parent != null) return;
                string [] arr = {"dlCentral add Remote Directory","Remote directory","","","",""};
                SetAddForm(arr);
                if (asf.ShowDialog() == DialogResult.OK)
                {
                    tvSites.SelectedNode.Nodes.Add(asf.textBox1.Text);
                    switch (tvSites.SelectedNode.Index)
                    {
                        case 0:
                            RTSites.Sites[i].TVRemoteDirs.Add(asf.textBox1.Text);
                            break;
                        case 1:
                            RTSites.Sites[i].MovieRemoteDirs.Add(asf.textBox1.Text);
                            break;
                        case 2:
                            RTSites.Sites[i].MP3RemoteDirs.Add(asf.textBox1.Text);
                            break;
                    }
                }
            }

            if (cMenuSites.SourceControl.Equals(lvTVSeries))
            {
                string[] arr = { "dlCentral add Replacement", "Original Name", "Modified Name", "Separator", "Season format", "Episode format" };
                SetAddForm(arr);
                asf.textBox3.Text = tbTVSeriesSeparator.Text;
                asf.textBox4.Text  = tbTVSeriesSeasonFormat.Text;
                asf.textBox5.Text = tbTVSeriesEpisodeFormat.Text;

                if (asf.ShowDialog() == DialogResult.OK)
                {
                    ListViewItem item = new ListViewItem(new[] { asf.textBox1.Text, asf.textBox2.Text, asf.textBox3.Text,
                                                                 asf.textBox4.Text, asf.textBox5.Text});
                    lvTVSeries.Items.Add(item); 
                   TVSeries item1 = new TVSeries();
                    item1.OriginalName = asf.textBox1.Text;
                    item1.ModifiedName = asf.textBox2.Text;
                    item1.Separator = asf.textBox3.Text;
                    item1.SeasonFormat = asf.textBox4.Text;
                    item1.EpisodeFormat = asf.textBox5.Text;
                    RTTVSeries.TVseries.Add(item1);
                }

            }
            if (cMenuSites.SourceControl.Equals(lbSites))
            {
                string[] arr = { "dlCentral add Site", "Site name", "", "", "", "" };
                SetAddForm(arr);
                if (asf.ShowDialog() == DialogResult.OK)
                {
                    if (asf.label1.Text.Length != 0)
                    {
                        SettingsSite tempSite = new SettingsSite();
                        tempSite.SiteName = asf.textBox1.Text;
                        RTSites.Sites.Add(tempSite);
                        lbSites.Items.Add(asf.textBox1.Text);
                        lbSites.SelectedIndex = lbSites.Items.Count - 1;
                    }
                }

            }

        }

        private void RemoveMI_Click(object sender, EventArgs e)
        {
            if (cMenuSites.SourceControl.Equals(tvSites))
            {
                int i = lbSites.SelectedIndex;
                if (i == -1) return;
                if (tvSites.SelectedNode.Parent == null) return;
                switch (tvSites.SelectedNode.Parent.Index)
                {
                    case 0:
                        RTSites.Sites[i].TVRemoteDirs.Remove(tvSites.SelectedNode.Text);
                        break;
                    case 1:
                        RTSites.Sites[i].MovieRemoteDirs.Remove(tvSites.SelectedNode.Text);
                        break;
                    case 2:
                        RTSites.Sites[i].MP3RemoteDirs.Remove(tvSites.SelectedNode.Text);
                        break;
                }
                tvSites.SelectedNode.Remove();
            }
            if (cMenuSites.SourceControl.Equals(lbSites))
            {
                int i = lbSites.SelectedIndex;
                PrevSiteIndex = -1;
                if (i != -1)
                {
                    RTSites.Sites.RemoveAt(i);
                    lbSites.Items.RemoveAt(i);
                }

            }
            if (cMenuSites.SourceControl.Equals(lvTVSeries))
            {
                int i = lvTVSeries.SelectedIndices[0];
                if (i != -1)
                {
                    lvTVSeries.Items.RemoveAt(i);
                    RTTVSeries.TVseries.RemoveAt(i);
                }

            }


        }

        private void btnCommDir_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog fb = new System.Windows.Forms.FolderBrowserDialog();
            fb.ShowNewFolderButton = true;
            fb.Description = "Select Folder:";
            DialogResult result = fb.ShowDialog();
            if (result == DialogResult.OK)
            {
                tbCommPath.Text = fb.SelectedPath;
            }
        }


        private void btnDir_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog fb = new System.Windows.Forms.FolderBrowserDialog();
            fb.ShowNewFolderButton = true;
            fb.Description = "Select Folder:";
            DialogResult result = fb.ShowDialog();
            if (result == DialogResult.OK)
            {
                if (sender == btnTVDir) tbTVLocalDir.Text = FileUtils.ensureBackSlash(fb.SelectedPath);
                if (sender == btnMovieDir) tbMovieLocalDir.Text = FileUtils.ensureBackSlash(fb.SelectedPath);
                if (sender == btnMP3Dir) tbMP3LocalDir.Text = FileUtils.ensureBackSlash(fb.SelectedPath);

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

//            Moviemeter m1 = new Moviemeter();
//            MovieDetail d1 = m1.GetMovieDetailFromIMDBID("tt0800320");

//            TheMovieDB m2 = new TheMovieDB();
//            MovieDetail d2 = m2.getMovieByImdb("tt0800320");
//            richTextBox1.Text = d2.Plot;

//            CT ih = new CT();

//            CinemaTorrents js = ih.GetRespons("http://cinematorrents.com/api/search?year=2010&year_op=GT&genre=thriller&rank=7&rank_op=GT");
            
//            foreach (CTObject item in js.Item)
//            {
//                richTextBox1.AppendText(item.enclosure_url);
                
//            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
                int i = lbSites.SelectedIndex;
                if (i == -1) return;
                if (i > 0)
                {
                    Object select, previous, temp;
                    select = RTSites.Sites[i];
                    previous = RTSites.Sites[i - 1];
                    temp = select;
                    select = previous;
                    previous = temp;
                    RTSites.Sites[i] = (SettingsSite)select;
                    RTSites.Sites[i - 1] = (SettingsSite)previous;
                    PrevSiteIndex = -1;

        			select = lbSites.Items[i];
		        	previous = lbSites.Items[i-1];
			        temp = select;
			        select = previous;
			        previous = temp;
			        lbSites.Items[i] = select;
			        lbSites.Items[i-1] = previous;
			        lbSites.SelectedIndex--;
                }
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
                int i = lbSites.SelectedIndex;
                if (i == -1 || i == lbSites.Items.Count-1) return;
                else
                {
                    Object select, next, temp;
                    select = RTSites.Sites[i];
                    next = RTSites.Sites[i + 1];
                    temp = select;
                    select = next;
                    next = temp;
                    RTSites.Sites[i] = (SettingsSite)select;
                    RTSites.Sites[i + 1] = (SettingsSite)next;
                    PrevSiteIndex = -1;

                    select = lbSites.Items[i];
                    next = lbSites.Items[i + 1];
                    temp = select;
                    select = next;
                    next = temp;
                    lbSites.Items[i] = select;
                    lbSites.Items[i + 1] = next;
                    lbSites.SelectedIndex++;

                }

        }


     
 

    }
}
